package com.javaweb.web.service.impl;

import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.javaweb.base.BaseDao;
import com.javaweb.base.po.File;
import com.javaweb.base.po.User;
import com.javaweb.constant.CommonConstant;
import com.javaweb.constant.SystemConstant;
import com.javaweb.db.query.QueryWapper;
import com.javaweb.util.core.FileUtil;
import com.javaweb.util.core.NumberFormatUtil;
import com.javaweb.util.core.ObjectOperateUtil;
import com.javaweb.util.entity.Page;
import com.javaweb.web.eo.file.FileListRequest;
import com.javaweb.web.eo.file.FileListResponse;
import com.javaweb.web.service.FileService;

/**
 * 文件模块业务层接口实现
 * 
 * @author tank2140896
 */
@Service("fileServiceImpl")
public class FileServiceImpl extends BaseDao implements FileService {

	/**
	 * 上传文件业务层接口实现
	 * 
	 * @param multipartFile multipartFile
	 * @param user 用户对象
	 * @return List<String> 文件ID列表
	 */
	@Transactional
	@Override
	public List<String> uploadFile(MultipartFile multipartFile[],User user) throws Exception {
		final String fileSerNo = UUID.randomUUID().toString();//文件批次号（同一批次上传的多个文件的批次号应该相同）
		List<String> list = new ArrayList<>();
		if(multipartFile!=null&&multipartFile.length>0){
    		for(int i=0;i<multipartFile.length;i++){
    			String id = idGenerator.idCreate();//文件唯一ID
    			String originFileName = multipartFile[i].getOriginalFilename();//原上传文件名称
    			String newFileName = UUID.randomUUID().toString()+"."+originFileName.split("\\.")[originFileName.split("\\.").length-1];//新文件名称
    			InputStream inputStream = multipartFile[i].getInputStream();
    			//FileUtil.writeFile(inputStream,new byte[1024],new File(filePath));
    			uploadFileByMinio(newFileName,inputStream);
    			File fileEntity = new File();
    			fileEntity.setId(id);
    			fileEntity.setSystemId(SystemConstant.SYSTEM_NO);
    			fileEntity.setFileUniqueIndex(UUID.randomUUID().toString());
    			fileEntity.setOriginFileName(originFileName);
    			fileEntity.setCurrentFileName(newFileName);
    			//fileEntity.setFilePath(filePath);
    			//fileEntity.setFileFullPath(fileFullPath);
    			fileEntity.setFileSuffix(newFileName.split("\\.")[newFileName.split("\\.").length-1]);
    			fileEntity.setFileSize(multipartFile[i].getSize());
    			fileEntity.setFileUnit("byte");
    			fileEntity.setFileSerNo(fileSerNo);
    			fileEntity.setFileUseType(2);
    			fileEntity.setCreator(user.getUserId());
    			fileEntity.setCreateDate(new Date());
    			fileEntity.setUpdater(user.getUserId());
    			fileEntity.setUpdateDate(new Date());
    			fileDao.insert(fileEntity);
    			list.add(id);
    		}
    	}
		return list;
	}
	
	/**
	 * 下载文件业务层接口实现
	 * 
	 * @param file 文件信息
	 * @param outputStream 输出流
	 */
	@Override
	public void downloadFile(File file,OutputStream outputStream) throws Exception {
		InputStream inputStream = downloadFileByMinio(file.getCurrentFileName());
		FileUtil.downloadFile(outputStream,new byte[1024],inputStream);
	}

	/**
	 * 文件列表业务层接口实现
	 * 
	 * @param fileListRequest 文件列表请求参数
	 * @return Page 分页参数
	 */
	@Override
	public Page list(FileListRequest fileListRequest) {
		QueryWapper<File> queryWapper = new QueryWapper<>();
		queryWapper.like(File::getOriginFileName,fileListRequest.getFileName());
		queryWapper.page(fileListRequest.getCurrentPage(),fileListRequest.getPageSize());
		List<File> list = fileDao.selectList(queryWapper);
		Long count = fileDao.selectListCount(queryWapper);
		List<FileListResponse> fileListResponseList = ObjectOperateUtil.copyListProperties(list,FileListResponse.class);
		fileListResponseList.stream().forEach(e->e.setFileSizeAndFileUnit(NumberFormatUtil.getdefaultFormatCapacity(new BigDecimal(e.getFileSize()))));
		Page page = new Page(fileListRequest,fileListResponseList,count);
		return page;
	}
	
	/**
	 * 文件删除业务层接口实现
	 * 
	 * @param id 文件ID
	 */
	@Transactional
	@Override
	public void fileDelete(String id) throws Exception {
		String ids[] = id.split(CommonConstant.COMMA);
		for(String eachId:ids){
			File file = fileDao.selectByPk(eachId);
			if(file!=null) {
				deleteFileByMinio(file.getCurrentFileName());
				fileDao.delete(eachId);
			}
		}
	}

	/**
	@Override
	public Page contentList(FileContentListRequest fileContentListRequest) {
		String fileFolderPath = fileContentListRequest.getFolderPath();
		if(fileFolderPath==null||CommonConstant.EMPTY_VALUE.equals(fileFolderPath)){//默认根路径
			if(SystemUtil.isLinux()){
				fileFolderPath = "/";
			}else{
				fileFolderPath = BaseInject.getFileRootPath().split(":\\\\")[0]+":\\";
			}
		}
		List<File> fileList = FileUtil.getAllFilesName(new File(fileFolderPath),new ArrayList<>(),false,false);
		long count = (fileList==null?0L:fileList.size());
		List<FileContentListResponse> responseList = new ArrayList<>(); 
		fileList = PageUtil.getSubList(fileList,fileContentListRequest.getPageSize(),fileContentListRequest.getCurrentPage());
		if(fileList!=null){
			for(int i=0;i<fileList.size();i++){
				FileContentListResponse fileContentListResponse = new FileContentListResponse();
				File eachFile = fileList.get(i);
				if(eachFile.isFile()){//文件
					String tempPath = fileFolderPath.replaceAll("\\\\","\\\\\\\\");
					if(!tempPath.endsWith("\\\\")){
						tempPath += "\\\\"; 
					}
					QueryWapper<com.javaweb.web.po.File> queryWapper = new QueryWapper<>();
					queryWapper.eq(com.javaweb.web.po.File.currentFileNameColumn,eachFile.getName());
					queryWapper.eq(com.javaweb.web.po.File.fileFullPathColumn,(tempPath+eachFile.getName()));
					com.javaweb.web.po.File fileDetail = fileDao.selectOne(queryWapper);
					if(fileDetail!=null){
						fileContentListResponse.setId(fileDetail.getId());
						fileContentListResponse.setCreateDate(fileDetail.getCreateDate());
						fileContentListResponse.setFileSizeAndFileUnit(NumberFormatUtil.getdefaultFormatCapacity(new BigDecimal(fileDetail.getFileSize())));
						fileContentListResponse.setFilePath(fileDetail.getFileFullPath());
						fileContentListResponse.setOriginFileName(fileDetail.getOriginFileName());
					}
				}
				fileContentListResponse.setFile(eachFile.isFile());//是否是文件
				fileContentListResponse.setName(eachFile.getName());//文件或目录名称
				fileContentListResponse.setFileAbsolutePath(eachFile.getAbsolutePath());//文件绝对路径
				responseList.add(fileContentListResponse);
			}
		}
		Page page = new Page(fileContentListRequest,responseList,count);
		return page;
	}

	@Override
	public com.javaweb.web.po.File fileDetail(String id) {
		return fileDao.selectByPk(id);
	}
	*/

}
